# _*_ coding:utf-8 _*_
# @File  : file_utils.py
# @Time  : 2022-03-27
# @Author: zizle
import os
import datetime
import pathlib
import random
import string
from configs import FILE_STORAGE


def generate_unique_filename(file_folder, filename, suffix, hashed=False):
    if hashed:
        filename = ''.join(random.sample(string.ascii_letters, 16))
    filepath = os.path.join(file_folder, "{}{}".format(filename, suffix))
    abs_filepath = os.path.join(FILE_STORAGE, filepath)
    if os.path.exists(abs_filepath):
        new_filename_suffix = ''.join(random.sample(string.ascii_letters, 6))
        new_filename = "{}_{}".format(filename, new_filename_suffix)
        return generate_unique_filename(file_folder, new_filename, suffix)
    else:
        return file_folder, filename, suffix


# 生成文件保存的绝对路径和SQL路径
def get_file_paths(module_name, filename, folder_root='Annexes', hashed=False, date_folder=None):
    # 保存附件到指定文件夹
    if not date_folder:
        date_folder = datetime.datetime.today().strftime('%Y%m')
    else:
        date_folder = date_folder
    # 创建文件保存所在的路径
    save_folder = "{}/{}/{}/".format(folder_root, module_name, date_folder)
    abs_folder = os.path.join(FILE_STORAGE, save_folder)
    if not os.path.exists(abs_folder):
        os.makedirs(abs_folder)
    pre_filename, file_suffix = os.path.splitext(filename)
    # 检测文件绝对路径名称是否存在,存在则需生成新的文件名，否则文件会被覆盖而使数据错误
    save_folder, new_filename, suffix = generate_unique_filename(save_folder, pre_filename, file_suffix, hashed=hashed)
    # print('save_folder:', save_folder)
    # print('new_filename:', new_filename)
    # print('suffix:', suffix)
    filename_saved = "{}{}".format(new_filename, suffix)
    save_path = os.path.join(abs_folder, filename_saved)
    sql_path = os.path.join(save_folder, filename_saved)
    return save_path, sql_path


# 读取文件夹下的图片文件
def get_file_list(folder: pathlib.Path, glob='*', replaces=None):
    file_list = []
    for f in folder.glob(glob):
        s = f.name
        if replaces:
            for i in replaces:
                s = s.replace(i, '')
            s = int(s)
        file_list.append({'s': s, 'f': f})
    file_list.sort(key=lambda x: x['s'])
    return [o['f'] for o in file_list]


# 去除文件后面的数字和后缀名称
def remove_filename_number_suffix(filename: str, number_max=10):
    name = filename.rsplit('.', 1)[0]
    for i in range(1, number_max):
        if name.endswith(f'({i})'):
            name = name.replace(f'({i})', '')
    return name


